# -*- coding: utf-8 -*-

import os
from datetime import datetime
import logging

from PIL import Image

from mpdev.exceptions import BadConfigurationError

logger = logging.getLogger(__name__)


class MediaProcessor:
    ANNOUNCEMENT_IMG = 'announcement_img_path'
    MOMENT_IMG = 'moment_img_path'
    GALBUM = 'galbum_img_path'
    GFILE = 'gfile_path'
    ACCOUNT_BANNER_IMG = 'account_banner_img_path'
    GROUP_IMG = 'group_img_path'

    DT_TO_FILENAME_FORMAT = '%Y%m%d%H%M%S%f'

    def __init__(self, blueprint=None):
        self.bp = None
        self.media_root = None
        self.thumbnail_size = None
        if blueprint is not None:
            self.init_blueprint(blueprint)

    def init_blueprint(self, blueprint):
        self.bp = blueprint
        blueprint.media_processor = self
        media_root = getattr(blueprint, 'media_root', None)
        if media_root is None:
            raise BadConfigurationError(u'必须为gzone模块设置有效media_root路径')
        if not os.path.isdir(media_root) or not os.path.isabs(media_root):
            raise BadConfigurationError(u'media_root路径配置不正确')
        self.media_root = media_root
        self.thumbnail_size = blueprint.app.config['GZONE_IMG_THUMBNAIL_SIZE']

    def get_file_path(self, filename, type_, with_root=False, *args, **kwargs):
        handler = getattr(self, '_get_' + type_, None)
        if handler is None:
            raise ValueError(u'不支持该类型文件路径生成')
        if with_root:
            path = handler(filename, *args, **kwargs)
            if isinstance(path, tuple):
                return tuple(os.path.join(self.media_root, p) for p in path)
            return os.path.join(self.media_root, path)
        return handler(filename, *args, **kwargs)

    def ensure_dir_exists(self, path):
        dir_path = os.path.dirname(path)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    def _get_announcement_img_path(self, filename, roomid):
        return os.path.join('images', 'announcement', roomid, filename)

    def _get_moment_img_path(self, filename, roomid, openid):
        return os.path.join('images', 'moment', roomid, openid, filename), \
               os.path.join('images', 'moment', roomid, openid, 'thumbnail', filename)

    def _get_galbum_img_path(self, filename, roomid, openid):
        return os.path.join('images', 'galbum', roomid, openid, filename), \
               os.path.join('images', 'galbum', roomid, openid, 'thumbnail', filename)

    def _get_gfile_path(self, filename, roomid, openid):
        return os.path.join('files', roomid, openid, filename)

    def _get_account_banner_img_path(self, filename):
        return os.path.join('images', 'banners', filename)

    def _get_group_img_path(self, filename, roomid):
        return os.path.join('images', 'group_images', roomid, filename)

    def process_filename(self, filename):
        processed = '{}{}'.format(
            datetime.now().strftime(self.DT_TO_FILENAME_FORMAT),
            os.path.splitext(filename)[1]
        )
        logger.debug('Processed filename: %s -> %s', filename, processed)
        return processed

    def generate_thumbnail(self, img):
        img = Image.open(img)
        img.thumbnail(self.thumbnail_size)
        return img
